﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace HigLabo.Net.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public static class DictionaryParserExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        public class RegexList
        {
            /// <summary>
            /// 
            /// </summary>
            public static readonly Regex YearMonth = new Regex("(?<Year>[0-9]{4})-(?<Month>[0-9]{2})");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="element"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static DateTime? ParseYearMonth(this Dictionary<String, Object> element, String key)
        {
            if (element.ContainsKey(key) == false) { return null; }
            Match m = RegexList.YearMonth.Match(element[key].ToString());
            if (m.Success == true)
            {
                Int32 year = Int32.Parse(m.Groups["Year"].Value);
                Int32 month = Int32.Parse(m.Groups["Month"].Value);
                if (month < 1 || month > 12) { return null; }
                return new DateTime(year, month, 1);
            }
            return null;
        }
    }
}
